
import PnApi from '../../api/PnApi'
import PnUtil from '../../utils/PnUtil'
import _ from "lodash";

import { getField, updateField } from 'vuex-map-fields';

const state = {

  // 临时存储全局变量，用于记录设计器的状态
  tmpLocalProp: 'ui9bmBvMSrSjJ2zmdGdg/tI6SCBgpWmN5YCW99+MJ7TdjjqQf/1NAcN2oPXAbbQww8LMqH9RHeerB+iasQ5owSDPU2sqMsYV',

  // 工程信息
  projectInfo: {},

  // 页面源数据
  pageMetadata: {
    layout: {
      layoutGroup: [

      ],
      layoutItems: [

      ]
    }
  },

  layoutHistory: {
    backwardRecord: [],
    backwardIndex: -2,
    recoverRecord: [],
    recoverIndex: -1
  },

  absoluteLayoutContainerWidth: 0,          // 设计器画布外层容器宽度

  structureTreeSidebarCollapsed: false,     // 结构树侧边栏收起状态
  componentLibrarySidebarCollapsed: false,  // 组件库侧边栏收起状态
  rightSidebarCollapsed: false,             // 右侧边栏收起状态
  canvasMapCollapsed: false,                // 画布映射收起状态

  rightSidebarPageConfigFormName: '',       // 右侧边栏页面信息编辑表单名称

  rightSidebarFuncCompConfigFormName: '',   // 右侧边栏组件编辑区表单名称

  currentSelectLayoutItemId: '',            // 当前选中的布局块ID
  currentSelectLayoutItemIds: [],           // 当前选中的多个布局块的ID数组
  currentHoverLayoutItemId: '',             // 当前滑入的布局块ID

  currentSelectGroupItemId: '',             // 当前选中的组项ID
  currentSelectGroupItemIds: [],            // 当前选中的多个组项的ID数组
  currentHoverGroupItemId: '',              // 当前滑入的组项ID

  canvasEnabled: true,                      // 画布激活状态
  keepCtrl: false,                          // 标识当前是否保持按住Ctrl按键（mac下会监听command按键），用于多选布局块或组时使用

  pageLinesData: {},                        // 设计器参考线数据
  zoomValue: 1,                             // 设计器画布缩放值

  purenessLayoutEditModel: false,           // 纯布局编辑模式
  autoSavePage: false,                      // 是否自动保存当前编辑页面
  autoSaveInterval: 3,                      // 自动保存时间间隔，默认3分钟

  rulerGuidesMagnetThreshold: 10,           // 标尺参考线磁吸阈值
  dragAlignMagnetThreshold: 5,              // 组件拖拽对齐参考线磁吸阈值

  alongShowTargetIdList: [],                // 被单独显示的布局块的ID集合

  adaptionDesignerCanvasZoom: true,         // 设计器画布自适应浏览器尺寸适配

  isAlongCompEditModel: false,              // 是否处于独立编辑组件状态
  alongCompEditCacheData: [],               // 独立编辑状态下的页面布局缓存数据

};

const getters = {
  getField,

  /**
   * 获取工程信息
   * @param state
   * @returns {state.projectInfo|{}|*|string}
   */
  getProjectInfo (state) {
    return state.projectInfo
  },

  /**
   * 获取页面源数据
   * @param state
   * @returns {state.pageMetadata|{layout}|*|string|EchartCompMixin.computed.pageMetadata|null}
   */
  getPageMetadata (state) {
    return state.pageMetadata
  },

  /**
   * 获取所有布局块对象
   * @param state
   * @returns {[]|*[]|{default: (function(): *[]), type}|{default: function(): [], type: ArrayConstructor}|{default: (function(): *[]), type}|{default: function(): [], type: Array | ArrayConstructor}}
   */
  getLayoutItems (state) {
    return state.pageMetadata.layout.layoutItems
  },

  /**
   * 获取布局块对象，内部根据currentSelectLayoutItemId状态属性来查询匹配的布局块对象
   * @param state
   * @returns {*}
   */
  getLayoutItem (state) {
    // let layoutItem = state.pageMetadata.layout.layoutItems.find(o=>o.id==state.currentSelectLayoutItemId);
    let layoutItem = {}
    for(let obj of state.pageMetadata.layout.layoutItems) {
      if (obj.id == state.currentSelectLayoutItemId) {
        layoutItem = obj
        if (layoutItem.component.id) {
          localStorage.setItem('currentSelectCompVersion', layoutItem.component.version)
        }
        return getField(layoutItem)
      }
    }
    return getField({})
  },

  getLayoutItemFromTree (state) {
    let layoutItem = {}
    let getTreeItem = (layoutItems) => {
      layoutItems.forEach(item => {
        if (item.id == state.currentSelectLayoutItemId) {
          layoutItem = item
        }else {
          if (item.children) {
            getTreeItem(item.children)
          }
        }
      })
    }
    getTreeItem(state.pageMetadata.layout.layoutItems)
    // if (layoutItem.component.id) {
    //   localStorage.setItem('currentSelectCompVersion', layoutItem.component.version)
    // }
    return getField(layoutItem)
  },

  /**
   * 根据布局块的ID获取布局块对象
   * @param state
   * @returns {function(*): *}
   */
  getLayoutItemById: (state) => (id) => {
    return state.pageMetadata.layout.layoutItems.find(o=>o.id==id)
  },

  getComponents (state) {
    let layoutItems = state.pageMetadata.layout.layoutItems;
    let components = [];
    layoutItems.forEach((item)=>{
      if(item.component.id) {
        components.push(item.component)
      }
    });
    return components;
  },

  /****************************************组相关操作****************************************/

  getLayoutGroup (state) {
    return state.pageMetadata.layout.layoutGroup
  },

  getGroupItem (state) {
    return getField(state.pageMetadata.layout.layoutGroup.find(o=>o.id==state.currentSelectGroupItemId))
  },

  getGroupItemById: (state) => (id) => {
    return state.pageMetadata.layout.layoutGroup.find(o=>o.id==id)
  },

  getLayoutGroupItemById: (state) => (id) => {
    return state.pageMetadata.layout.layoutGroup.find(o=>o.id==id)
  },

  /****************************************组相关操作 end ****************************************/

  getKeepCtrl (state) {
    return state.keepCtrl
  },

  getPageLinesData (state) {
    return state.pageLinesData
  },

  getZoomValue (state) {
    return state.zoomValue
  },

  getPurenessLayoutEditModel () {
    return state.purenessLayoutEditModel
  },

  getIsAlongCompEditModel () {
    return state.isAlongCompEditModel
  },

  getAlongCompEditCacheData () {
    return state.alongCompEditCacheData
  }

};

const actions = {

  loadPage ({commit, state}, pageId) {
    return new Promise((resolve, reject) => {
      PnApi.DesignerApi.getDesignerData(pageId).then(result => {
        let pageMetadata = result.data.payload;
        if (pageMetadata.theme_json) {
          pageMetadata.theme_json = JSON.parse(pageMetadata.theme_json);
        }
        pageMetadata.layout = JSON.parse(pageMetadata.layout);
        if (!pageMetadata.layout.layoutConfigData.designPhaseNotLoadGlobalStyle) {
          pageMetadata.layout.layoutConfigData.pageGlobalStyleCode ? PnUtil.insertStyle(pageMetadata.layout.layoutConfigData.pageGlobalStyleCode) : undefined
        }
        pageMetadata.layout.layoutConfigData.pageGlobalJsCode ? PnUtil.insertScript(pageMetadata.layout.layoutConfigData.pageGlobalJsCode) : undefined
        commit('setPageMetadata', pageMetadata);
        commit('resetLayoutHistory');
        resolve()
      })
    })
  },

  /**
   * 布局设计器撤销操作
   * @param commit
   * @param state
   */
  stepBackward ({commit, state}) {
    if (state.layoutHistory.backwardIndex > -1) {
      let recoverLayoutItem = _.last(state.layoutHistory.backwardRecord);
      recoverLayoutItem.history = true;
      commit('addRecoverRecordItem', recoverLayoutItem);
      let tmpLayoutItem = state.layoutHistory.backwardRecord[state.layoutHistory.backwardIndex];
      tmpLayoutItem.history = true;
      commit('setLayout', _.cloneDeep(tmpLayoutItem));
      commit('deleteBackwardRecordLastItem');
      commit('setBackwardIndex', -1);
    }
  },

  /**
   * 布局设计器恢复操作
   * @param commit
   * @param state
   */
  stepRecover ({commit, state}) {
    if (state.layoutHistory.recoverIndex > -1) {
      commit('addBackwardRecordItem', state.layoutHistory.recoverRecord[state.layoutHistory.recoverIndex]);
      let tmpLayoutItem = state.layoutHistory.recoverRecord[state.layoutHistory.recoverIndex];
      tmpLayoutItem.history = true;
      commit('setLayout', _.cloneDeep(tmpLayoutItem));
      commit('setRecoverIndex', -1);
    }
  }

};

const mutations = {

  updateField,

  /**
   * 重置设计器相关状态
   * @param state
   */
  resetDesigner (state) {
    // 清空布局块相关数据
    state.currentSelectLayoutItemId = '';
    state.currentSelectLayoutItemIds = [];
    state.currentHoverLayoutItemId = '';

    // 清空组相关数据
    state.currentSelectGroupItemId = '';
    state.currentHoverGroupItemId = '';
    state.currentSelectGroupItemIds = [];

    state.rightSidebarFuncCompConfigFormName = '';

    state.pageMetadata.layout.layoutItems = [];
    state.pageMetadata.layout.layoutGroup = [];

    state.alongShowTargetIdList = [];
  },

  /**
   * 清空所有选中状态，包括布局块与组
   * @param state
   */
  clearAllSelected (state) {
    state.currentSelectLayoutItemId = '';
    state.currentSelectLayoutItemIds = [];
    state.currentHoverLayoutItemId = '';

    state.currentSelectGroupItemId = '';
    state.currentHoverGroupItemId = '';
    state.currentSelectGroupItemIds = [];

    state.rightSidebarFuncCompConfigFormName = '';
  },

  setAbsoluteLayoutContainerWidth (state, width) {
    state.absoluteLayoutContainerWidth = width
  },

  setProjectInfo (state, projectInfo) {
    state.projectInfo = projectInfo
  },

  setPageMetadata (state, pageMetadata) {
    state.pageMetadata = pageMetadata
  },

  setPageCreateDate (state, createDate) {
    state.pageMetadata.create_date = createDate
  },

  setPagePublishAndEncrypt (state, payload) {
    state.pageMetadata.publish = payload.publish;
    state.pageMetadata.encrypt = payload.encrypt;
    state.pageMetadata.password = payload.password;
  },

  setPageThemeJson (state, payload) {
    state.pageMetadata.theme_json = payload
  },

  toggleStructureTreeSidebarCollapsed (state) {
    state.structureTreeSidebarCollapsed = !state.structureTreeSidebarCollapsed
  },

  toggleComponentLibrarySidebarCollapsed (state) {
    state.componentLibrarySidebarCollapsed = !state.componentLibrarySidebarCollapsed
  },

  toggleRightSidebarCollapsed (state) {
    state.rightSidebarCollapsed = !state.rightSidebarCollapsed
  },

  toggleCanvasMapCollapsed (state) {
    state.canvasMapCollapsed = !state.canvasMapCollapsed
  },

  /**
   * 设置layout对象
   * @param state
   * @param layout
   */
  setLayout (state, layout) {
    state.pageMetadata.layout = layout
  },

  /**
   *
   * @param state
   * @param layoutConfigData
   */
  setLayoutConfigData (state, layoutConfigData) {
    state.pageMetadata.layout.layoutConfigData = layoutConfigData
  },

  /**
   *
   * @param state
   * @param layoutItems
   */
  setLayoutItems (state, layoutItems) {
    state.pageMetadata.layout.layoutItems = layoutItems
  },

  /**
   * 删除指定布局块绑定的组件
   * @param state
   * @param layoutItemId
   */
  deleteComponentByLayoutItemId (state, layoutItemId) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==layoutItemId);
    obj.component = {}
  },

  /**
   * 设置布局块别名
   * @param state
   * @param payload
   */
  setLayoutItemAliasName (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.aliasName = payload.aliasName
  },

  /**
   * 设置布局块的左和上偏移
   * @param state
   * @param payload
   */
  setLayoutItemLeftAndTop (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.left = payload.left;
    obj.layoutItemConfigData.top = payload.top;
  },

  /**
   * 响应式栅格布局中，设置布局块的x和y
   * @param state
   * @param payload
   */
  setReactiveLayoutItemXAndY (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.x = payload.x;
    obj.layoutItemConfigData.y = payload.y;
  },

  /**
   * 设置布局块的左和上偏移（用于方向键调整位置时使用）
   * @param state
   * @param payload
   */
  setLayoutItemLeftAndTopOffset (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData[payload.direction] = obj.layoutItemConfigData[payload.direction] + payload.offset;
  },

  /**
   * 设置布局块的宽、高、左偏移、上偏移的偏移（在多选布局块时，调整某个布局块的尺寸时会调用此函数同步调整其他被选布局块的尺寸）
   * @param state
   * @param payload
   */
  setLayoutItemWhltOffset (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.left = obj.layoutItemConfigData.left + payload.offsetLeft;
    obj.layoutItemConfigData.top = obj.layoutItemConfigData.top + payload.offsetTop;
    let newWidth = obj.layoutItemConfigData.width + payload.offsetWidth;
    if (obj.layoutItemConfigData.width + payload.offsetWidth <= 10) {
      newWidth = 10
    }
    obj.layoutItemConfigData.width = newWidth;
    let newHeight = obj.layoutItemConfigData.height + payload.offsetHeight;
    if (obj.layoutItemConfigData.height + payload.offsetHeight <= 10) {
      newHeight = 10
    }
    obj.layoutItemConfigData.height = newHeight;
  },

  /**
   * 当组项进行拖拽调整尺寸时，调用此函数，进行组内布局块的等比例调整尺寸
   * @param state
   * @param payload
   */
  setLayoutItemWhltOffsetFromGroupResize (state, payload) {
    let layoutItem = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);

    let verticalZoomScale = 1 + payload.offsetHeight/payload.originalGroupItemWhlt.height;  // 垂直缩放比例
    let horizontalZoomScale = 1 + payload.offsetWidth/payload.originalGroupItemWhlt.width;  // 水平缩放比例

    // 组的left坐标往左偏移，即拖动左侧或左上角、左下角手柄往左移动（算法暂不明确，暂时取消使用）
    /*if (payload.offsetLeft != 0) {
      if (payload.offsetWidth != 0) {
        // 最右侧布局块
        if (layoutItem.layoutItemConfigData.left + layoutItem.layoutItemConfigData.width == payload.originalGroupItemWhlt.width + payload.originalGroupItemWhlt.left) {
          let tmpWidth = layoutItem.layoutItemConfigData.width;
          layoutItem.layoutItemConfigData.width = parseInt((layoutItem.layoutItemConfigData.width * horizontalZoomScale).toFixed())
          layoutItem.layoutItemConfigData.left -= (layoutItem.layoutItemConfigData.width - tmpWidth)
        }else {
          layoutItem.layoutItemConfigData.width = parseInt((layoutItem.layoutItemConfigData.width * horizontalZoomScale).toFixed())
          layoutItem.layoutItemConfigData.left += payload.offsetLeft
        }
      }
    }*/
    // 组的top坐标往上偏移，即拖动上侧或左上角、左下角手柄往上移动（算法暂不明确，暂时取消使用）
    /*if (payload.offsetTop != 0) {
      if (payload.offsetHeight != 0) {
        // 最下侧布局块
        if (layoutItem.layoutItemConfigData.top + layoutItem.layoutItemConfigData.height == payload.originalGroupItemWhlt.height + payload.originalGroupItemWhlt.top) {
          let tmpHeight = layoutItem.layoutItemConfigData.height;
          layoutItem.layoutItemConfigData.height = parseInt((layoutItem.layoutItemConfigData.height * verticalZoomScale).toFixed())
          layoutItem.layoutItemConfigData.top -= (layoutItem.layoutItemConfigData.height - tmpHeight)
        }
        // 最上侧布局块
        else if (layoutItem.layoutItemConfigData.top == payload.originalGroupItemWhlt.top) {
          layoutItem.layoutItemConfigData.height = parseInt((layoutItem.layoutItemConfigData.height * verticalZoomScale).toFixed())
          layoutItem.layoutItemConfigData.top += payload.offsetTop
        }
        // 其他
        else {
          layoutItem.layoutItemConfigData.height = parseInt((layoutItem.layoutItemConfigData.height * verticalZoomScale).toFixed())
          layoutItem.layoutItemConfigData.top += payload.offsetTop
        }
      }
    }*/
    if (payload.offsetLeft == 0 && payload.offsetTop == 0) {

      if (payload.offsetHeight != 0) {
        // 最上侧的布局块top坐标保持不变
        if (layoutItem.layoutItemConfigData.top == payload.originalGroupItemWhlt.top) {
          layoutItem.layoutItemConfigData.height = parseInt((layoutItem.layoutItemConfigData.height * verticalZoomScale).toFixed())
        }else {
          let tmpTop = layoutItem.layoutItemConfigData.top - payload.originalGroupItemWhlt.top;
          layoutItem.layoutItemConfigData.top = parseInt((tmpTop * verticalZoomScale).toFixed()) + payload.originalGroupItemWhlt.top
          layoutItem.layoutItemConfigData.height = parseInt((layoutItem.layoutItemConfigData.height * verticalZoomScale).toFixed())
        }
      }
      if (payload.offsetWidth != 0) {
        // 最左侧的布局块left坐标保持不变
        if (layoutItem.layoutItemConfigData.left == payload.originalGroupItemWhlt.left) {
          layoutItem.layoutItemConfigData.width = parseInt((layoutItem.layoutItemConfigData.width * horizontalZoomScale).toFixed())
        }else {
          let tmpLeft = layoutItem.layoutItemConfigData.left - payload.originalGroupItemWhlt.left;
          layoutItem.layoutItemConfigData.left = parseInt((tmpLeft * horizontalZoomScale).toFixed()) + payload.originalGroupItemWhlt.left
          layoutItem.layoutItemConfigData.width = parseInt((layoutItem.layoutItemConfigData.width * horizontalZoomScale).toFixed())
        }
      }

    }
  },

  /**
   * 设置布局块的层级zIndex
   * @param state
   * @param payload
   */
  setLayoutItemZIndex (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    if (payload['topOne']) {
      obj.layoutItemConfigData.zIndex += 1;
    } else if (payload['downOne']) {
      // obj.layoutItemConfigData.zIndex > 1 ? obj.layoutItemConfigData.zIndex -= 1 : obj.layoutItemConfigData.zIndex == 1
      obj.layoutItemConfigData.zIndex -= 1
    } else {
      obj.layoutItemConfigData.zIndex = payload.zIndex;
    }
  },

  /**
   * 设置布局块的宽度和高度
   * @param state
   * @param payload
   */
  setLayoutItemWidthAndHeight (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.width = payload.width;
    obj.layoutItemConfigData.height = payload.height;
  },

  /**
   * 响应式栅格布局中，设置布局块的w和h
   * @param state
   * @param payload
   */
  setReactiveLayoutItemWAndH (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.w = payload.w;
    obj.layoutItemConfigData.h = payload.h;
  },

  /**
   * 设置布局块的宽度、高度、左偏移、右偏移
   * @param state
   * @param payload
   */
  setLayoutItemWhlt (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.width = payload.width;
    obj.layoutItemConfigData.height = payload.height;
    obj.layoutItemConfigData.left = payload.left;
    obj.layoutItemConfigData.top = payload.top;
  },

  /**
   * 设置布局块的显示隐藏
   * @param state
   * @param payload
   */
  setLayoutItemDisplay (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.display = payload.display
  },

  /**
   * 设置布局块是否允许拖拽
   * @param state
   * @param payload
   */
  setLayoutItemDraggableEnabled (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.draggableEnabled = payload.draggableEnabled
  },

  /**
   * 反向设置布局块是否允许拖拽
   * @param state
   * @param payload
   */
  setLayoutItemDraggableEnabledReverse (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.draggableEnabled = !obj.layoutItemConfigData.draggableEnabled
  },

  /**
   * 设置布局块是否静止不动（响应式栅格布局中使用）
   * @param state
   * @param payload
   */
  setLayoutItemIsStatic (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.isStatic = !obj.layoutItemConfigData.isStatic
  },

  /**
   * 设置布局块过渡动画相关配置
   * @param state
   * @param payload
   */
  setLayoutItemAnimationSetting (state, payload) {
    let obj = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.id);
    obj.layoutItemConfigData.animationVisible = payload.animationVisible;
    obj.layoutItemConfigData.animationDelay = payload.animationDelay;
    obj.layoutItemConfigData.inAnimation = payload.inAnimation;
    obj.layoutItemConfigData.outAnimation = payload.outAnimation;
  },

  /**
   * 添加布局块
   * @param state
   * @param layoutItem
   */
  addLayoutItem(state, layoutItem) {
    state.pageMetadata.layout.layoutItems.push(layoutItem)
  },

  /**
   * 删除布局块
   * @param state
   * @param layoutItemId
   */
  deleteLayoutItem(state, layoutItemId) {
    let layoutItems = state.pageMetadata.layout.layoutItems;
    let del = function (layoutItems) {
      layoutItems.map((item, index) => {
        if (item.id == layoutItemId) {
          layoutItems.splice(index, 1)
        }
        if (item.children) {
          del(item.children)
        }
      })
    }
    del(layoutItems)
    // for (let i = 0; i < layoutItems.length; i++) {
    //   if(layoutItems[i].id === layoutItemId) {
    //     layoutItems.splice(i, 1);
    //     i--
    //   }
    // }
  },

  /**
   * 添加组件到布局块
   * @param state
   * @param payload
   */
  addComponentToLayoutItem (state, payload) {
    let layoutItem = state.pageMetadata.layout.layoutItems.find(o=>o.id==payload.layoutItemId);
    layoutItem.component = payload.component
  },

  /**
   * 设置右侧边栏页面信息编辑表单名称
   * @param state
   * @param payload
   */
  setRightSidebarPageConfigFormName (state, payload) {
    state.rightSidebarPageConfigFormName = payload
  },

  /**
   * 设置当前选中的单个布局块ID
   * @param state
   * @param layoutItemId
   */
  setCurrentSelectLayoutItemId (state, layoutItemId) {
    state.currentSelectLayoutItemId = layoutItemId;
  },

  /**
   * 设置当前滑入的布局块ID
   * @param state
   * @param layoutItemId
   */
  setCurrentHoverLayoutItemId (state, layoutItemId) {
    state.currentHoverLayoutItemId = layoutItemId;
  },

  /**
   * 设置所有布局块是否可拖拽配置
   * @param state
   * @param enabled
   */
  setAllLayoutItemDraggableEnabled (state, payload) {
    state.pageMetadata.layout.layoutItems.forEach(layoutItem => {
      layoutItem.layoutItemConfigData.draggableEnabled = payload.enabled
    })
  },

  /**
   * 设置所有布局块的显示与隐藏
   * @param state
   * @param payload
   */
  setAllLayoutItemDisplay (state, payload) {
    state.pageMetadata.layout.layoutItems.forEach(layoutItem => {
      layoutItem.layoutItemConfigData.display = payload.display
    })
  },

  updateLayoutItem (state, field) {
    updateField(state.pageMetadata.layout.layoutItems.find(o=>o.id==state.currentSelectLayoutItemId), field);
  },

  updateLayoutItemFromTree (state, field) {
    let layoutItem = {}
    let getTreeItem = (layoutItems) => {
      layoutItems.forEach(item => {
        if (item.id == state.currentSelectLayoutItemId) {
          layoutItem = item
        }else {
          if (item.children) {
            getTreeItem(item.children)
          }
        }
      })
    }
    getTreeItem(state.pageMetadata.layout.layoutItems)
    updateField(layoutItem, field)
  },

  /**
   * 设置 右侧边栏组件配置关联的组件表单名
   * @param state
   * @param payload
   */
  setRightSidebarFuncCompConfigFormName (state, payload) {
    state.rightSidebarFuncCompConfigFormName = payload
  },


  /**
   * 添加 当前选中的多个布局块的ID数组 项
   * @param state
   * @param layoutItemId
   */
  addIdToCurrentSelectLayoutItemIds (state, layoutItemId) {
    state.currentSelectLayoutItemIds.pushNoRepeat(layoutItemId)
  },

  /**
   * 设置 当前选中的多个布局块的ID数组
   * @param state
   * @param layoutItemIds 一个存储布局块ID字符串的数组
   */
  setCurrentSelectLayoutItemIds (state, layoutItemIds) {
    state.currentSelectLayoutItemIds = layoutItemIds
  },

  /**
   * 设置 画布激活状态
   * @param state
   * @param enabled
   */
  setCanvasEnabled (state, enabled) {
    state.canvasEnabled = enabled
  },

  /****************************************布局设计器回退与恢复操作****************************************/

  resetLayoutHistory (state) {
    state.layoutHistory = {
      backwardRecord: [],
      backwardIndex: -2,
      recoverRecord: [],
      recoverIndex: -1
    }
  },

  addBackwardRecordItem (state, layoutData) {
    state.layoutHistory.backwardRecord.push(layoutData);
    state.layoutHistory.backwardIndex += 1
  },

  addRecoverRecordItem (state, layoutData) {
    state.layoutHistory.recoverRecord[0] = layoutData;
    state.layoutHistory.recoverIndex = 0
  },

  deleteBackwardRecordLastItem (state) {
    state.layoutHistory.backwardRecord.pop();
  },

  setBackwardIndex (state, index) {
    state.layoutHistory.backwardIndex += index
  },

  setRecoverIndex (state, index) {
    state.layoutHistory.recoverIndex += index
  },

  /****************************************布局设计器回退与恢复操作 end****************************************/

  /****************************************组相关操作****************************************/

  updateGroupItem (state, field) {
    updateField(state.pageMetadata.layout.layoutGroup.find(o=>o.id==state.currentSelectGroupItemId), field);
  },

  setLayoutGroup (state, layoutGroup) {
    state.pageMetadata.layout.layoutGroup = layoutGroup
  },

  setCurrentSelectGroupItemId (state, groupItemId) {
    state.currentSelectGroupItemId = groupItemId
  },

  addIdToCurrentSelectGroupItemIds (state, groupItemId) {
    state.currentSelectGroupItemIds.pushNoRepeat(groupItemId)
  },

  setCurrentSelectGroupItemIds (state, groupItemIds) {
    state.currentSelectGroupItemIds = groupItemIds
  },

  setCurrentHoverGroupItemId (state, groupItemId) {
    state.currentHoverGroupItemId = groupItemId;
  },

  addLayoutGroupItem (state, groupItem) {
    state.pageMetadata.layout.layoutGroup.push(groupItem)
  },

  setGroupItemWidthAndHeight (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData.width = payload.width;
    obj.groupItemConfigData.height = payload.height;
  },

  setGroupItemLeftAndTop (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData.left = payload.left;
    obj.groupItemConfigData.top = payload.top;
  },

  setGroupItemLeftAndTopOffset (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData[payload.direction] = obj.groupItemConfigData[payload.direction] + payload.offset;
  },

  setGroupItemWhlt (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData.width = payload.width;
    obj.groupItemConfigData.height = payload.height;
    obj.groupItemConfigData.left = payload.left;
    obj.groupItemConfigData.top = payload.top;
  },

  setGroupItemZIndex (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData.zIndex = payload.zIndex
  },

  setGroupItemName (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.name = payload.name
  },

  setGroupItemDraggable (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData.draggable = payload.draggable
  },

  setGroupItemDraggableReverse (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData.draggable = !obj.groupItemConfigData.draggable
  },

  setGroupItemDisplay (state, payload) {
    let obj = state.pageMetadata.layout.layoutGroup.find(o=>o.id==payload.id);
    obj.groupItemConfigData.display = payload.display
  },

  setAllGroupItemDraggableEnabled (state, payload) {
    state.pageMetadata.layout.layoutGroup.forEach(groupItem => {
      groupItem.groupItemConfigData.draggable = payload.enabled
    })
  },

  setAllGroupItemDisplay (state, payload) {
    state.pageMetadata.layout.layoutGroup.forEach(groupItem => {
      groupItem.groupItemConfigData.display = payload.display
    })
  },

  /**
   * 删除组项
   * @param state
   * @param groupItemId
   */
  deleteGroupItem (state, groupItemId) {
    let layoutGroup = state.pageMetadata.layout.layoutGroup;
    for (let i = 0; i < layoutGroup.length; i++) {
      if(layoutGroup[i].id === groupItemId) {
        layoutGroup.splice(i, 1);
        i--
      }
    }
  },

  /**
   * 删除组内布局块ID项
   * @param state
   * @param layoutItemId
   */
  deleteGroupItemLayoutItemId (state, layoutItemId) {
    let layoutGroup = state.pageMetadata.layout.layoutGroup;
    if(layoutGroup) {
      layoutGroup.forEach(groupItem => {
        let layoutItemIds = groupItem.layoutItemIds;
        for (let i=0; i<layoutItemIds.length; i++) {
          if (layoutItemIds[i] === layoutItemId) {
            layoutItemIds.splice(i, 1);
            i--
          }
        }
      })
    }
  },

  /**
   * 将多个布局块添加至某个组中
   * @param state
   * @param payload
   */
  addLayoutItemsToGroupItem(state, payload) {
    let layoutGroup = state.pageMetadata.layout.layoutGroup;
    layoutGroup.forEach(groupItem => {
      if (groupItem.id === payload.targetGroupItemId) {
        groupItem.layoutItemIds = _.concat(groupItem.layoutItemIds, payload.newLayoutItemIds)
      }
    })
  },

  /**
   * 从某个组中移出多个布局块
   * @param state
   * @param payload
   */
  shiftOutLayoutItemsFromGroupItem(state, payload) {
    let layoutGroup = state.pageMetadata.layout.layoutGroup;
    layoutGroup.forEach(groupItem => {
      if (groupItem.id === payload.targetGroupItemId) {
        groupItem.layoutItemIds = _.remove(groupItem.layoutItemIds, function (n) {
          return payload.layoutItemIds.indexOf(n) < 0
        })
      }
    })
  },

  /****************************************组相关操作 end ****************************************/

  setKeepCtrl (state, payload) {
    state.keepCtrl = payload
  },

  setPageLinesData (state, pageLinesData) {
    state.pageLinesData = pageLinesData
  },

  setZoomValue (state, value) {
    state.zoomValue = value
  },

  setPurenessLayoutEditModel (state, value) {
    state.purenessLayoutEditModel = value
  },

  setAlongShowTargetIdList (state, payload) {
    state.alongShowTargetIdList = payload
  },

  resetAlongShowTargetIdList (state) {
    state.alongShowTargetIdList = []
  },

  setIsAlongCompEditModel (state, payload) {
    state.isAlongCompEditModel = payload
  },

  setAlongCompEditCacheData (state, payload) {
    state.alongCompEditCacheData = payload
  }

};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

